package com.h3c.nem.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eos.common.constant.StatusCodeEnum;
import com.eos.common.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.h3c.nem.annotation.CheckRole;
import com.h3c.nem.dto.SdFileTemplateDTO;
import com.h3c.nem.entity.SdFileTemplate;
import com.h3c.nem.enums.FileOpTypeEnum;
import com.h3c.nem.service.CommService;
import com.h3c.nem.service.ISdFileTemplateService;
import com.h3c.nem.utils.AppBusinessException;
import com.h3c.nem.utils.ReturnCodeData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: SdFileTemplateController
 *
 * @Author: l22886
 * @Date: 2021-06-16
 * Description: sd_file_template controller
 * Version: 1.0
 */
@Api(tags = " SdFileTemplate 接口")
@Slf4j
@CrossOrigin
@RestController
@RequestMapping(value = "/sdFileTemplate", produces = "application/json;charset=utf-8")
public class SdFileTemplateController {

    @Resource
    private ISdFileTemplateService sdFileTemplateService;
    @Autowired
    private CommService commService;

    @CheckRole
    @ApiOperation(value = "新增或修改excel模板文件", notes = "新增或修改excel模板文件")
    @PostMapping(value = "/addSdFileTemplate")
    public Result addSdFileTemplate(SdFileTemplateDTO pdFileTemplateDTO) {
        sdFileTemplateService.addSdFileTemplate(pdFileTemplateDTO);
        if( pdFileTemplateDTO.getUploadTemplateFile()!=null){
            MultipartFile templateFile = pdFileTemplateDTO.getUploadTemplateFile();
            commService.recordFileOperationLog(templateFile.getOriginalFilename(), templateFile.getSize(), FileOpTypeEnum.IMPORT);
        }
        return new Result(true, StatusCodeEnum.ADD_SUCCESS);
    }

    @CheckRole
    @ApiOperation(value = "删除excel模板文件", notes = "删除excel模板文件")
    @RequestMapping(value = "/deleteSdFileTemplate", method = RequestMethod.POST)
    public Result deleteSdFileTemplate(@RequestBody SdFileTemplateDTO pdFileTemplateDTO) {
        sdFileTemplateService.deleteSdFileTemplate(pdFileTemplateDTO);
        return new Result(true, StatusCodeEnum.REMVOE_SUCCESS);
    }

    @RequestMapping("/downloadTmp/{templateCode}")
    @ResponseBody
    public Map<String,String> downLoadTemplate(@PathVariable("templateCode") String templateCode,
                                               HttpServletRequest request,
                                               HttpServletResponse response) {
        try {
            SdFileTemplate pdFileTemplateDO = sdFileTemplateService.queryTemplateByCode(templateCode);
            String templateId = pdFileTemplateDO.getFileTemplateId();
            String fileNameWithPah = pdFileTemplateDO.getTemplateFilePath();
            String fileName = fileNameWithPah.substring(fileNameWithPah.lastIndexOf("\\")+1);
            fileName = pdFileTemplateDO.getTemplateName()+fileName.substring(fileName.lastIndexOf("."));

//            File downloadFile = new File();
//            FileInputStream inputFile = new FileInputStream(downloadFile);
            byte[] buffer = pdFileTemplateDO.getTemplateFile();
//            inputFile.read(buffer);
//            inputFile.close();
            Map<String,String> result = new HashMap<String,String>();
            result.put("file", Base64Utils.encodeToString(buffer));
            result.put("filename", fileName);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("文件下载异常");
        }
    }

    @ApiOperation(value = "下载excel模板文件", notes = "下载excel模板文件")
    @PostMapping(value = "/downloadExcelTemplate")
    @ResponseBody
    public Map<String, String> downloadExcelTemplate(@RequestBody SdFileTemplateDTO pdFileTemplateDTO) {
        try {
            SdFileTemplate tempateDo = sdFileTemplateService.queryOrigFileTemplate(pdFileTemplateDTO);
            String filePath = tempateDo.getTemplateFilePath();
            String templateCode = tempateDo.getTemplateCode();
            Map<String, String> result = new HashMap<>();
            byte[] bytes = tempateDo.getOrigTemplateFile();
            String name = templateCode + (filePath.substring(filePath.lastIndexOf(".")));
            commService.recordFileOperationLog(name, (long) bytes.length, FileOpTypeEnum.EXPORT);
            result.put("file", Base64Utils.encodeToString(bytes));
            result.put("filename", name);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppBusinessException("文件下载异常");
        }
    }


    /**
     * @title: queryFuzzyListForPage
     * @description: 列表分页模糊查询
     * @params: [ paramsDTO, currentPage, pageSize ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2021-06-16
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "查询excel模板", notes = "查询excel模板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "SdFileTemplateDTO", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "一页数据条数", required = true, dataType = "Integer", paramType = "query")
    })
    @CheckRole
    @RequestMapping(value = "/queryFuzzyListForPage", method = RequestMethod.GET)
    public ResponseEntity<JSONObject> queryFuzzyListForPage(@ModelAttribute SdFileTemplateDTO paramsDTO,
                                                            @RequestParam(name = "currentPage", required = true) Integer currentPage,
                                                            @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        log.info("准备执行  列表分页模糊查询，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //分页
            Page page = PageHelper.startPage(currentPage, pageSize);
            //执行
            List<SdFileTemplateDTO> resultDTOList = sdFileTemplateService.selectFuzzyByDto(paramsDTO);
            resultDTOList.forEach(dto -> {
                dto.setOrigTemplateFile(null);
                dto.setTemplateFile(null);
            });

            PageInfo<SdFileTemplateDTO> pageInfo = page.toPageInfo();
            pageInfo.setList(resultDTOList);
            data.put("data", pageInfo);
            data.put("msg", "列表分页模糊查询成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行列表分页模糊查询异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行列表分页模糊查询完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

}
